package com.umeox.watch.moto.chat.db

import androidx.room.*

/**
 * Created by Rambo 2021/8/18
 * Describe:
 */
@Dao
interface ChatMessageDao {

    @Query("SELECT * FROM chat_info WHERE (fuid = :friendId AND type == 0) OR (tuid = :friendId AND type == 0) ORDER BY msgId ASC,id ASC")
    fun loadAllMessageByFriendId(friendId: String): MutableList<ChatMessage?>?

    @Query("SELECT * FROM chat_info WHERE tuid = :friendId AND type == 1 ORDER BY msgId ASC,id ASC")
    fun loadGroupMessageByFriendId(friendId: String): MutableList<ChatMessage?>?

    @Query("SELECT COUNT(*) FROM chat_info WHERE (fuid = :friendId AND msgTime >= :todayMillis) OR (tuid = :friendId AND msgTime >= :todayMillis)")
    fun loadMsgCountByFriendId(friendId: String, todayMillis: Long): Int

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun save(chatMessage: ChatMessage): Long

    @Query("SELECT MAX(msgId) FROM chat_info")
    fun getMaxMsgId(): String?

    @Query("SELECT MAX(msgTime) FROM chat_info")
    fun getMaxMsgTime(): Long?

    @Update
    fun update(chatMessage: ChatMessage): Int

    @Query("UPDATE chat_info SET unRead = :readState WHERE id = :id")
    fun updateUnreadById(id: Long, readState: Int): Int

    @Delete
    fun delete(chatMessages: List<ChatMessage>)

    @Query("DELETE FROM chat_info WHERE (fuid = :uid AND type == 0) OR (tuid = :uid AND type == 0)")
    fun deleteByFriendId(uid: String): Int

    @Query("SELECT min(id) FROM (SELECT * FROM chat_info WHERE fuid = :fuid OR tuid =:fuid ORDER BY msgId DESC LIMIT 100)")
    fun queryMinIDInLatest100(fuid: String): Long

    @Query("SELECT * FROM chat_info WHERE id < :id AND (fuid = :fuid OR tuid = :fuid)")
    fun queryBeforeLatest100(fuid: String, id: Long): List<ChatMessage>

    @Query("SELECT id FROM chat_info WHERE msgId = :msgId")
    fun queryIdByMsgId(msgId: String): Long

    @Query("UPDATE chat_info SET unRead = :readState WHERE msgType != 1 AND fuid = :friendId")
    fun updateReadStateWithoutVoiceType(friendId: String, readState: Int)

    @Query("SELECT count(id) FROM chat_info WHERE unRead = :readState AND fuid = :friendId")
    fun queryUnReadCount(readState: Int, friendId: String): Int

    @Query("UPDATE chat_info SET state = :state WHERE id = :id")
    fun updateChatMessageState(state: Int, id: Long): Int

    @Query("DELETE FROM chat_info")
    fun deleteAll(): Int

}